package org.blackcat.web.filter;

import com.alibaba.fastjson.JSONObject;
import org.blackcat.core.annotation.Login;
import org.blackcat.domain.common.MsgResponse;
import org.blackcat.domain.enums.ResponseCodeEnum;
import org.blackcat.domain.enums.UserEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Duo Duo on 2017/1/5.
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private LoginedUser loginedUser;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        if(o.getClass().isAssignableFrom(HandlerMethod.class)){
            String token = loginedUser.getToken(request);
            request.setAttribute(UserEnum.USER_REQUEST_TOKEN.getValue(),token);
            Login login = ((HandlerMethod)o).getMethodAnnotation(Login.class);
            if(login == null || login.value() == false){
                return true;
            }else{
                if(token == null){
                    MsgResponse<Object> msg = new MsgResponse<Object>(ResponseCodeEnum.USER_CHECK_LOGIN,"未登录，请登录");
                    String rs = JSONObject.toJSONString(msg);
                    response.getOutputStream().write(rs.getBytes("UTF-8"));
                    return false;
                }
                request.setAttribute(UserEnum.USER_REQUEST_TOKEN.getValue(),token);
                return true;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
